#include "CairoSurface.h"

#include <QImage>
#include <QPainter>

#include <QDebug>

#define M_PI 3.1415926535898

CairoSurface::CairoSurface(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);

    _img = new QImage(size(), QImage::Format_ARGB32);
    _img->fill(Qt::white);

    _surface = cairo_image_surface_create_for_data(_img->bits(), CAIRO_FORMAT_ARGB32,
        _img->width(), _img->height(), _img->bytesPerLine());

    cairo_surface_set_device_scale(_surface, 1, 1);

    _context = cairo_create(_surface);

    cairo_set_source_rgb(_context, 1.0, 0.0, 0.0);

    cairo_set_line_width(_context,2.0);
    cairo_set_line_join(_context, cairo_line_join_t::CAIRO_LINE_JOIN_ROUND);
    cairo_set_line_cap(_context, cairo_line_cap_t::CAIRO_LINE_CAP_SQUARE);
 
    cairo_move_to(_context,50, 50);
    cairo_line_to(_context, 100, 100);
    cairo_line_to(_context, 100, 50);
    cairo_stroke(_context);

  /*  cairo_rectangle(_context, width() / 2, height() / 2, 50, 50);
    cairo_stroke(_context);

    cairo_arc(_context, 200, 200, 50, 0, M_PI * 2);
    cairo_stroke(_context);*/

    //cairo_set_source_rgba(_context, 0.0, 1.0, 0.0, 0.5);
    //for (int i = 0; i < width(); i += 5) {
    //    for (int j = 0; j < height(); j += 5) {
    //        cairo_arc(_context, i, j, 1, 0, M_PI * 2);
    //        cairo_stroke(_context);
    //    }
    //}
}

CairoSurface::~CairoSurface()
{
    cairo_destroy(_context);
    cairo_surface_destroy(_surface);
}

void CairoSurface::paintEvent(QPaintEvent * event)
{
    auto data = cairo_image_surface_get_data(_surface);
    auto w = cairo_image_surface_get_width(_surface);
    auto h = cairo_image_surface_get_height(_surface);
    auto stride = cairo_image_surface_get_stride(_surface);

    QPainter painter(this);
    painter.drawImage(0, 0, *_img);

    //QMainWindow::paintEvent(event);

}
